<template>
  <div class="page">
    <div class="page-header">
      <h1>安全评价计算</h1>
      <p>基于AHP-MIV-BP模型进行矿山安全等级智能评估</p>
      <div class="header-actions">
        <!-- <button class="btn btn-secondary" @click="loadEvaluationList">
          <i class="fas fa-list"></i> 查看历史评价
        </button> -->
      </div>
    </div>
    
    <!-- 评价列表 -->
    <div v-if="showHistory" class="evaluation-history">
      <div class="section-header">
        <h3>历史评价记录</h3>
        <button class="btn btn-primary" @click="showHistory = false">
          <i class="fas fa-plus"></i> 新建评价
        </button>
      </div>
      
      <div class="history-list">
        <div v-if="evaluationHistory.length === 0" class="empty-state">
          <p>暂无评价记录</p>
        </div>
        <div v-else class="evaluation-cards">
          <div 
            v-for="evaluation in evaluationHistory" 
            :key="evaluation.id"
            class="evaluation-card"
            @click="loadEvaluationDetail(evaluation.id)"
          >
            <div class="card-header">
              <h4>{{ evaluation.mine_name }}</h4>
              <span class="evaluation-id">{{ evaluation.evaluation_id }}</span>
            </div>
            <div class="card-body">
              <p><strong>评价人：</strong>{{ evaluation.evaluator_name }}</p>
              <p><strong>评价日期：</strong>{{ evaluation.evaluation_date }}</p>
              <p><strong>所属区域：</strong>{{ evaluation.region_display || evaluation.region }}</p>
              <p><strong>类别：</strong>{{ evaluation.evaluation_category_display || evaluation.evaluation_category }}</p>
            </div>
            <div class="card-footer">
              <div class="safety-info">
                <!-- <span class="safety-score">综合得分: {{ evaluation.comprehensive_score }}</span> -->
                <span class="safety-level" :class="getSafetyLevelClass(evaluation.safety_level)">{{ evaluation.safety_level }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 评价表单 -->
    <div v-if="!showHistory" class="evaluation-form">
      <div class="form-section">
        <h3>矿山基本信息</h3>
        <div class="form-grid">
          <div class="form-group">
            <label>评价编号</label>
            <input type="text" v-model="evaluationForm.evaluation_id" readonly placeholder="系统自动生成">
          </div>
          <div class="form-group">
            <label>评价日期</label>
            <input type="date" v-model="evaluationForm.evaluation_date">
          </div>
          <div class="form-group">
            <label>评价人</label>
            <input type="text" v-model="evaluationForm.evaluator_name" placeholder="请输入评价人姓名">
          </div>
          <div class="form-group">
            <label>矿山名称</label>
            <input type="text" v-model="evaluationForm.mine_name" placeholder="请输入矿山名称">
          </div>
          <div class="form-group">
            <label>隶属企业名字</label>
            <input type="text" v-model="evaluationForm.affiliated_enterprise" placeholder="请输入隶属企业名称">
          </div>
          <div class="form-group">
            <label>生产能力（万吨/年）</label>
            <input type="number" v-model="evaluationForm.production_capacity" min="0" step="0.1" placeholder="请输入生产能力">
          </div>
          <div class="form-group">
            <label>服务年限（年）</label>
            <input type="number" v-model="evaluationForm.service_life" min="0" step="1" placeholder="请输入服务年限">
          </div>
          <div class="form-group">
            <label>所属区域</label>
            <select v-model="evaluationForm.region">
              <option value="">请选择区域</option>
              <option v-for="region in regionOptions" :key="region.value" :value="region.value">
                {{ region.label }}
              </option>
            </select>
          </div>
          <div class="form-group">
            <label>评价对象类别</label>
            <select v-model="evaluationForm.evaluation_category">
              <option value="">请选择类别</option>
              <option value="coal_mine">煤矿</option>
              <option value="metal_mine">金属矿</option>
              <option value="non_metal_mine">非金属矿</option>
            </select>
          </div>
          <div class="form-group">
            <label>开拓方式</label>
            <div class="checkbox-group">
              <label v-for="method in developmentMethodOptions" :key="method.value" class="checkbox-label">
                <input 
                  type="checkbox" 
                  :value="method.value" 
                  v-model="evaluationForm.development_methods"
                >
                {{ method.label }}
              </label>
            </div>
          </div>
          <div class="form-group">
            <label>运输方式</label>
            <div class="radio-group">
              <label v-for="method in transportMethodOptions" :key="method.value" class="radio-label">
                <input 
                  type="radio" 
                  :value="method.value" 
                  v-model="evaluationForm.transport_method"
                >
                {{ method.label }}
              </label>
            </div>
          </div>
        </div>
      </div>

      <!-- 生产系统信息模块 -->
      <div class="form-section">
        <h3>生产系统信息</h3>
        <div class="production-system-container">
          <div class="form-group">
            <label>选择生产系统</label>
            <select v-model="evaluationForm.current_production_system">
              <option v-for="system in productionSystemOptions" :key="system.value" :value="system.value">
                {{ system.label }}
              </option>
            </select>
          </div>
          
          <div class="selected-system-form">
            <h4>{{ evaluationForm.production_systems[evaluationForm.current_production_system].system_name }}</h4>
            <div class="system-form">
              <div class="form-group">
                <label>系统名称</label>
                <input type="text" v-model="evaluationForm.production_systems[evaluationForm.current_production_system].system_name" readonly>
              </div>
              <div class="form-group">
                <label>功能描述</label>
                <input type="text" v-model="evaluationForm.production_systems[evaluationForm.current_production_system].function_description" readonly>
              </div>
              <div class="form-group">
                <label>主要设施</label>
                <input type="text" v-model="evaluationForm.production_systems[evaluationForm.current_production_system].main_facilities" placeholder="请输入主要设施">
              </div>
              <div class="form-group">
                <label>运行状态</label>
                <div class="radio-group">
                  <label v-for="status in operationStatusOptions" :key="status.value" class="radio-label">
                    <input 
                      type="radio" 
                      :value="status.value" 
                      v-model="evaluationForm.production_systems[evaluationForm.current_production_system].operation_status"
                    >
                    {{ status.label }}
                  </label>
                </div>
              </div>
              <div class="form-group">
                <label>安全隐患</label>
                <textarea v-model="evaluationForm.production_systems[evaluationForm.current_production_system].safety_hazards" placeholder="请输入安全隐患" rows="3"></textarea>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="form-section">
        <h3>安全指标数据 (15项)</h3>
        <div class="indicators-grid">
          <div class="indicator-category" v-for="category in indicatorCategories" :key="category.name">
            <h4>{{ category.name }}</h4>
            <div class="form-group" v-for="indicator in category.indicators" :key="indicator.key">
              <label>
                {{ indicator.name }}
                <span class="indicator-help" :title="indicator.help">
                  <i class="fas fa-question-circle"></i>
                </span>
              </label>
              <input 
                type="number" 
                step="0.1" 
                min="0" 
                max="100" 
                v-model="evaluationForm[indicator.key]"
                :placeholder="`默认值: ${indicator.default}`"
              >
              <small class="indicator-desc">{{ indicator.help }}</small>
            </div>
          </div>
        </div>
      </div>

      <div class="form-actions">
        <!-- <button class="btn btn-secondary" @click="loadDefaultValues" :disabled="isLoading">
          <i class="fas fa-refresh"></i>
          加载默认值
        </button> -->
        <button class="btn btn-primary" @click="saveEvaluation" :disabled="isLoading">
          <i class="fas fa-save" v-if="!isLoading"></i>
          <i class="fas fa-spinner fa-spin" v-if="isLoading"></i>
          {{ currentEvaluationId ? '更新评价' : '保存评价' }}
        </button>
      </div>
    </div>

    <!-- 计算结果 -->
    <div v-if="evaluationResult && !showHistory" class="result-section">
      <h3>评价结果</h3>
      <div class="result-grid">
        <div class="result-card">
          <h4>安全等级</h4>
          <div class="safety-level" :class="getSafetyLevelClass(evaluationResult.safety_level)">
            {{ evaluationResult.safety_level }}
          </div>
        </div>
        <!-- <div class="result-card">
          <h4>综合得分</h4>
          <div class="safety-score">{{ evaluationResult.comprehensive_score }}</div>
        </div> -->
        <div class="result-card">
          <h4>评价编号</h4>
          <div class="evaluation-info">{{ evaluationResult.evaluation_id }}</div>
        </div>
        <div class="result-card">
          <h4>矿山名称</h4>
          <div class="evaluation-info">{{ evaluationResult.mine_name }}</div>
        </div>
      </div>
      
      <div class="form-actions">
        <button class="btn btn-info" @click="generateSafetyReport" :disabled="isGeneratingReport">
          <i class="fas fa-file-alt" v-if="!isGeneratingReport"></i>
          <i class="fas fa-spinner fa-spin" v-if="isGeneratingReport"></i>
          {{ isGeneratingReport ? '生成中...' : '生成安全报告' }}
        </button>
        <button class="btn btn-success" @click="exportReport" :disabled="isExporting">
          <i class="fas fa-download" v-if="!isExporting"></i>
          <i class="fas fa-spinner fa-spin" v-if="isExporting"></i>
          {{ isExporting ? '导出中...' : '导出评价报告' }}
        </button>
        <button class="btn btn-secondary" @click="resetForm">
          <i class="fas fa-plus"></i>
          新建评价
        </button>
      </div>
    </div>
    
    <!-- 安全报告弹窗 -->
    <div v-if="showReportModal" class="report-modal-overlay" @click="closeReportModal">
      <div class="report-modal" @click.stop>
        <div class="modal-header">
          <h3><i class="fas fa-file-alt"></i> 矿山安全评价报告</h3>
          <button class="close-btn" @click="closeReportModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        
        <div class="modal-body">
          <div v-if="safetyReportData" class="report-content">
            <!-- 报告基本信息 -->
            <div class="report-section">
              <h4>报告基本信息</h4>
              <div class="info-grid">
                <div class="info-item" v-for="(value, key) in safetyReportData['报告基本信息']" :key="key">
                  <span class="label">{{ key }}：</span>
                  <span class="value">{{ value }}</span>
                </div>
              </div>
            </div>
            
            <!-- 矿山基本信息 -->
            <div class="report-section">
              <h4>矿山基本信息</h4>
              <div class="info-grid">
                <div class="info-item" v-for="(value, key) in safetyReportData['矿山基本信息']['信息项']" :key="key">
                  <span class="label">{{ key }}：</span>
                  <span class="value">{{ value }}</span>
                </div>
              </div>
            </div>
            
            <!-- 安全等级判定 -->
            <!--
            <div class="report-section">
              <h4>安全等级判定</h4>
              <div class="safety-result">
                <div class="safety-level-display" :class="getSafetyLevelClass(safetyReportData['安全等级判定']['总体安全等级'])">
                  {{ safetyReportData['安全等级判定']['总体安全等级'] }}
                </div>
                <div class="safety-details">
                  <p><strong>低分指标数量：</strong>{{ safetyReportData['安全等级判定']['低分指标数量'] }}</p>
                  <p><strong>建议整改指标：</strong>{{ safetyReportData['安全等级判定']['建议整改指标'] }}</p>
                </div>
              </div>
            </div>
            -->
            
            <!-- 安全指标评分 -->
            <div class="report-section">
              <h4>安全指标评分与模型计算</h4>
              <div class="indicators-table">
                <table>
                  <thead>
                    <tr>
                      <th>序号</th>
                      <th>指标名称</th>
                      <th>指标值</th>
                      <th>权重</th>
                      <th>期望输出值</th>
                      <th>模型输出值</th>
                      <th>偏差/误差</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="indicator in safetyReportData['安全指标评分与模型计算']" :key="indicator['序号']">
                      <td>{{ indicator['序号'] }}</td>
                      <td>{{ indicator['指标名称'] }}</td>
                      <td :class="indicator['指标值'] < 50 ? 'low-score' : ''">{{ indicator['指标值'] }}</td>
                      <td>{{ indicator['权重'] }}</td>
                      <td>{{ indicator['期望输出值'] }}</td>
                      <td>{{ indicator['模型输出值'] }}</td>
                      <td>{{ indicator['偏差/误差'] }}</td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            
            <!-- 整改建议 -->
            <div class="report-section" v-if="safetyReportData['整改建议'] && safetyReportData['整改建议'].length > 0">
              <h4>整改建议</h4>
              <div class="remediation-suggestions">
                <div v-for="(suggestion, index) in safetyReportData['整改建议']" :key="index" class="suggestion-item">
                  <div class="suggestion-header">
                    <span class="indicator-name">{{ suggestion['指标名称'] }}</span>
                    <span class="safety-level" :class="getSafetyLevelClass(suggestion['安全等级'])">{{ suggestion['安全等级'] }}</span>
                  </div>
                  <div class="suggestion-condition">
                    <strong>触发条件：</strong>{{ suggestion['触发条件'] }}
                  </div>
                  <div class="suggestion-content">
                    {{ suggestion['建议内容'] }}
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 报告元数据 -->
            <div class="report-section">
              <h4>报告元数据</h4>
              <div class="info-grid">
                <div class="info-item" v-for="(value, key) in safetyReportData['报告元数据']" :key="key">
                  <span class="label">{{ key }}：</span>
                  <span class="value">{{ value }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeReportModal">
            <i class="fas fa-times"></i>
            关闭
          </button>
          <button class="btn btn-success" @click="exportReportToPDF" :disabled="isExportingPDF">
            <i class="fas fa-file-pdf" v-if="!isExportingPDF"></i>
            <i class="fas fa-spinner fa-spin" v-if="isExportingPDF"></i>
            {{ isExportingPDF ? '导出中...' : '导出PDF' }}
          </button>
          <button class="btn btn-primary" @click="downloadReportJSON">
            <i class="fas fa-download"></i>
            下载JSON报告
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { api } from '../api/index'

// 状态管理
const isLoading = ref(false)
const isExporting = ref(false)
const isGeneratingReport = ref(false)
const isExportingPDF = ref(false)
const showHistory = ref(false)
const showReportModal = ref(false)
const evaluationResult = ref<any>(null)
const evaluationHistory = ref<any[]>([])
const currentEvaluationId = ref<number | null>(null)
const safetyReportData = ref<any>(null)

// 评价表单数据
const evaluationForm = reactive<any>({
  evaluation_id: '',
  evaluation_date: new Date().toISOString().split('T')[0],
  evaluator_name: '',
  mine_name: '',
  region: '',
  evaluation_category: '',
  
  // 新增矿山基本信息字段
  affiliated_enterprise: '', // 隶属企业名字
  production_capacity: 100, // 生产能力（万吨/年）
  service_life: 30, // 服务年限（年）
  development_methods: [], // 开拓方式（多选：斜井、立井、平硐）
  transport_method: '', // 运输方式（单选：电机车运输、带式运送机运输）
  
  // 生产系统信息
  current_production_system: 'mining_system', // 当前选中的系统
  production_systems: {
    mining_system: {
      system_name: '开采系统',
      function_description: '矿石开采',
      main_facilities: '掘进机、采煤机',
      operation_status: 'normal',
      safety_hazards: '顶板监测需加强'
    },
    ventilation_system: {
      system_name: '通风系统',
      function_description: '矿井通风',
      main_facilities: '主扇风机、局部通风机',
      operation_status: 'normal',
      safety_hazards: '通风阻力较大'
    },
    gas_prevention_system: {
      system_name: '瓦斯防治系统',
      function_description: '瓦斯监测与防治',
      main_facilities: '瓦斯监测仪、抽放设备',
      operation_status: 'normal',
      safety_hazards: '监测点覆盖不全'
    },
    drainage_system: {
      system_name: '排水系统',
      function_description: '矿井排水',
      main_facilities: '主排水泵、水仓',
      operation_status: 'normal',
      safety_hazards: '排水能力需提升'
    },
    hoisting_transport_system: {
      system_name: '提升运输系统',
      function_description: '物料提升运输',
      main_facilities: '提升机、运输机',
      operation_status: 'normal',
      safety_hazards: '提升设备老化'
    },
    power_system: {
      system_name: '供电系统',
      function_description: '矿井供电',
      main_facilities: '变压器、配电柜',
      operation_status: 'normal',
      safety_hazards: '供电线路需检修'
    },
    fire_explosion_prevention_system: {
      system_name: '防火防爆系统',
      function_description: '防火防爆',
      main_facilities: '消防设备、防爆设备',
      operation_status: 'normal',
      safety_hazards: '消防设备配置不足'
    }
  },
  
  // 15个安全指标（使用数据库字段名，范围0-100）
  worker_safety_awareness: 75.0,
  management_capability: 80.0,
  mining_equipment_integrity: 85.0,
  ventilation_equipment_integrity: 90.0,
  gas_monitoring_equipment_integrity: 88.0,
  fire_prevention_equipment_integrity: 82.0,
  drainage_equipment_integrity: 87.0,
  hoisting_equipment_integrity: 91.0,
  power_system_integrity: 89.0,
  air_supply_demand_ratio: 78.0,
  roof_management_difficulty: 70.0,
  coal_spontaneous_combustion_tendency: 65.0,
  safety_management_implementation: 83.0,
  emergency_response_completeness: 77.0,
  safety_inspection_implementation: 81.0,
})

// 区域选项
const regionOptions = ref([
  { value: 'beijing', label: '北京市' },
  { value: 'tianjin', label: '天津市' },
  { value: 'hebei', label: '河北省' },
  { value: 'shanxi', label: '山西省' },
  { value: 'inner_mongolia', label: '内蒙古自治区' },
  { value: 'liaoning', label: '辽宁省' },
  { value: 'jilin', label: '吉林省' },
  { value: 'heilongjiang', label: '黑龙江省' },
  { value: 'shanghai', label: '上海市' },
  { value: 'jiangsu', label: '江苏省' },
  { value: 'zhejiang', label: '浙江省' },
  { value: 'anhui', label: '安徽省' },
  { value: 'fujian', label: '福建省' },
  { value: 'jiangxi', label: '江西省' },
  { value: 'shandong', label: '山东省' },
  { value: 'henan', label: '河南省' },
  { value: 'hubei', label: '湖北省' },
  { value: 'hunan', label: '湖南省' },
  { value: 'guangdong', label: '广东省' },
  { value: 'guangxi', label: '广西壮族自治区' },
  { value: 'hainan', label: '海南省' },
  { value: 'chongqing', label: '重庆市' },
  { value: 'sichuan', label: '四川省' },
  { value: 'guizhou', label: '贵州省' },
  { value: 'yunnan', label: '云南省' },
  { value: 'tibet', label: '西藏自治区' },
  { value: 'shaanxi', label: '陕西省' },
  { value: 'gansu', label: '甘肃省' },
  { value: 'qinghai', label: '青海省' },
  { value: 'ningxia', label: '宁夏回族自治区' },
  { value: 'xinjiang', label: '新疆维吾尔自治区' },
])

// 开拓方式选项
const developmentMethodOptions = ref([
  { value: 'inclined_shaft', label: '斜井' },
  { value: 'vertical_shaft', label: '立井' },
  { value: 'adit', label: '平硐' }
])

// 运输方式选项
const transportMethodOptions = ref([
  { value: 'electric_locomotive', label: '电机车运输' },
  { value: 'belt_conveyor', label: '带式运送机运输' }
])

// 运行状态选项
const operationStatusOptions = ref([
  { value: 'normal', label: '正常' },
  { value: 'attention', label: '注意' },
  { value: 'abnormal', label: '异常' }
])

// 生产系统选项
const productionSystemOptions = ref([
  { value: 'mining_system', label: '开采系统' },
  { value: 'ventilation_system', label: '通风系统' },
  { value: 'gas_prevention_system', label: '瓦斯防治系统' },
  { value: 'drainage_system', label: '排水系统' },
  { value: 'hoisting_transport_system', label: '提升运输系统' },
  { value: 'power_system', label: '供电系统' },
  { value: 'fire_explosion_prevention_system', label: '防火防爆系统' }
])

// 指标分类配置
const indicatorCategories = ref([
  {
    name: '人员因素',
    indicators: [
      { 
        key: 'worker_safety_awareness', 
        name: '工人安全意识与操作能力', 
        default: 75.0,
        help: '评价工人对安全操作规程的认知和执行能力，范围0-100'
      },
      { 
        key: 'management_capability', 
        name: '管理人员的管理能力', 
        default: 80.0,
        help: '评价管理层的安全管理水平和决策能力，范围0-100'
      }
    ]
  },
  {
    name: '设备因素',
    indicators: [
      { 
        key: 'mining_equipment_integrity', 
        name: '采掘设备完好率', 
        default: 85.0,
        help: '采掘设备的完好状态和可靠性评价，范围0-100'
      },
      { 
        key: 'ventilation_equipment_integrity', 
        name: '矿井通风设备完好率', 
        default: 90.0,
        help: '通风系统设备的完好程度，范围0-100'
      },
      { 
        key: 'gas_monitoring_equipment_integrity', 
        name: '瓦斯监测设备完好率', 
        default: 88.0,
        help: '瓦斯监测预警设备的完好状态，范围0-100'
      },
      { 
        key: 'fire_prevention_equipment_integrity', 
        name: '防火及消防设施完好率', 
        default: 82.0,
        help: '防火消防设施的完好程度和有效性，范围0-100'
      },
      { 
        key: 'drainage_equipment_integrity', 
        name: '井下排水设备完好率', 
        default: 87.0,
        help: '排水系统设备的完好状态，范围0-100'
      },
      { 
        key: 'hoisting_equipment_integrity', 
        name: '矿井提升设备完好率', 
        default: 91.0,
        help: '提升运输设备的完好程度，范围0-100'
      },
      { 
        key: 'power_system_integrity', 
        name: '供电系统设备完好率', 
        default: 89.0,
        help: '供配电系统的完好状态和稳定性，范围0-100'
      }
    ]
  },
  {
    name: '环境因素',
    indicators: [
      { 
        key: 'air_supply_demand_ratio', 
        name: '风量供需比', 
        default: 78.0,
        help: '矿井风量供给与需求的比值，范围0-100'
      },
      { 
        key: 'roof_management_difficulty', 
        name: '顶板管理难易程度', 
        default: 70.0,
        help: '顶板支护管理的难易程度，数值越高表示管理越容易，范围0-100'
      },
      { 
        key: 'coal_spontaneous_combustion_tendency', 
        name: '煤层自燃发火倾向性', 
        default: 65.0,
        help: '煤层自燃发火的倾向性，数值越高表示自燃倾向性越低，范围0-100'
      }
    ]
  },
  {
    name: '管理因素',
    indicators: [
      { 
        key: 'safety_management_implementation', 
        name: '安全管理制度及落实率', 
        default: 83.0,
        help: '安全管理制度的完善程度和执行情况，范围0-100'
      },
      { 
        key: 'emergency_response_completeness', 
        name: '应急响应机制完善率', 
        default: 77.0,
        help: '应急预案和响应机制的完善程度，范围0-100'
      },
      { 
        key: 'safety_inspection_implementation', 
        name: '安全检查整改落实率', 
        default: 81.0,
        help: '安全检查发现问题的整改落实情况，范围0-100'
      }
    ]
  }
])

// 加载默认指标值
const loadDefaultValues = async () => {
  try {
    isLoading.value = true
    const response = await api.evaluation.getDefaultIndicators()
    
    if (response.success) {
      // 加载安全指标默认值
      if (response.data.indicators) {
        Object.assign(evaluationForm, response.data.indicators)
      }
      
      // 加载矿山基本信息默认值
      if (response.data.mine_basic_info) {
        Object.assign(evaluationForm, response.data.mine_basic_info)
      }
    }
  } catch (error) {
    console.error('加载默认值失败:', error)
    // alert('加载默认值失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 保存评价
const saveEvaluation = async () => {
  try {
    // 表单验证
    if (!evaluationForm.evaluator_name || !evaluationForm.mine_name || !evaluationForm.region || !evaluationForm.evaluation_category) {
      alert('请填写完整的矿山基本信息')
      return
    }
    
    // 验证新增字段
    if (evaluationForm.production_capacity <= 0) {
      alert('生产能力必须大于0')
      return
    }
    
    if (evaluationForm.service_life <= 0) {
      alert('服务年限必须大于0')
      return
    }
    
    if (evaluationForm.development_methods.length === 0) {
      alert('请至少选择一种开拓方式')
      return
    }
    
    if (!evaluationForm.transport_method) {
      alert('请选择运输方式')
      return
    }
    
    isLoading.value = true
    
    let response
    if (currentEvaluationId.value) {
      // 更新现有评价
      response = await api.evaluation.update(currentEvaluationId.value, evaluationForm)
    } else {
      // 创建新评价
      response = await api.evaluation.create(evaluationForm)
    }
    
    if (response.success) {
      currentEvaluationId.value = response.data.id
      evaluationResult.value = response.data
      
      // 确保安全等级正确显示
      if (response.data.safety_level) {
        evaluationResult.value.safety_level = response.data.safety_level
      }
      
      alert(currentEvaluationId.value ? '安全报告更新成功！' : '安全报告创建成功！')
      
      // 滚动到结果区域
      setTimeout(() => {
        const resultSection = document.querySelector('.result-section')
        if (resultSection) {
          resultSection.scrollIntoView({ behavior: 'smooth' })
        }
      }, 100)
    }
  } catch (error) {
    console.error('保存安全报告失败:', error)
    alert('保存失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 加载评价列表（暂时注释掉，因为当前界面没有使用）
// const loadEvaluationList = async () => {
//   try {
//     const response = await api.evaluation.list()
//     if (response.success) {
//       evaluationHistory.value = response.data.evaluations
//       showHistory.value = true
//     }
//   } catch (error) {
//     console.error('加载评价列表失败:', error)
//     alert('加载列表失败，请重试')
//   }
// }

// 加载评价详情
const loadEvaluationDetail = async (id: number) => {
  try {
    const response = await api.evaluation.detail(id)
    if (response.success) {
      const data = response.data
      
      // 填充基本信息
      Object.assign(evaluationForm, {
        evaluation_id: data.evaluation_id,
        evaluation_date: data.evaluation_date,
        evaluator_name: data.evaluator_name,
        mine_name: data.mine_name,
        region: data.region,
        evaluation_category: data.evaluation_category,
        
        // 新增矿山基本信息字段
        affiliated_enterprise: data.affiliated_enterprise || '',
        production_capacity: data.production_capacity || 100.0,
        service_life: data.service_life || 30,
        development_methods: data.development_methods || [],
        transport_method: data.transport_method || '',
        
        // 生产系统信息
        current_production_system: data.current_production_system || 'mining_system',
        production_systems: data.production_systems || {},
        
        // 安全指标
        ...data.indicators
      })
      
      currentEvaluationId.value = id
      evaluationResult.value = data
      showHistory.value = false
      
      // 确保安全等级正确显示
      if (data.safety_level) {
        evaluationResult.value.safety_level = data.safety_level
      }
    }
  } catch (error) {
    console.error('加载评价详情失败:', error)
    alert('加载详情失败，请重试')
  }
}

// 生成安全报告
const generateSafetyReport = async () => {
  if (!currentEvaluationId.value) {
    alert('请先创建或选择一个评价记录')
    return
  }
  
  try {
    isGeneratingReport.value = true
    const response = await api.evaluation.generateSafetyReport(currentEvaluationId.value)
    
    if (response.success) {
      safetyReportData.value = response.data
      showReportModal.value = true
      console.log('安全报告数据:', response.data)
      
      // 从报告中提取安全等级和综合得分，更新数据库
      const safetyLevelData = response.data['安全等级判定']
      if (safetyLevelData && safetyLevelData['总体安全等级']) {
        try {
          // 使用后端提供的准确综合得分
          const comprehensiveScore = safetyLevelData['综合得分']
          
          if (comprehensiveScore !== undefined && comprehensiveScore !== null) {
            // 调用API更新数据库中的安全等级
            const updateResponse = await api.evaluation.updateSafetyLevel(currentEvaluationId.value, {
              safety_level: safetyLevelData['总体安全等级'],
              comprehensive_score: comprehensiveScore
            })
            
            if (updateResponse.success) {
              console.log('安全等级已更新到数据库:', updateResponse.data)
              // 更新前端显示的安全等级
              if (evaluationResult.value) {
                evaluationResult.value.safety_level = safetyLevelData['总体安全等级']
                evaluationResult.value.comprehensive_score = comprehensiveScore
              }
            } else {
              console.error('更新安全等级失败:', updateResponse.error)
            }
          } else {
            console.warn('报告中缺少综合得分信息')
          }
        } catch (updateError) {
          console.error('更新安全等级时发生错误:', updateError)
        }
      }
      
      // 显示评估完成提示
      alert('评估完成！' + (response.message ? '\n' + response.message : ''))
    } else {
      alert('生成安全报告失败：' + (response.error || '未知错误'))
    }
  } catch (error) {
    console.error('生成安全报告失败:', error)
    alert('生成安全报告失败，请重试')
  } finally {
    isGeneratingReport.value = false
  }
}

// 关闭报告弹窗
const closeReportModal = () => {
  showReportModal.value = false
  safetyReportData.value = null
}

// 下载JSON报告
const downloadReportJSON = () => {
  if (!safetyReportData.value) return
  
  try {
    const dataStr = JSON.stringify(safetyReportData.value, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)
    
    const link = document.createElement('a')
    link.href = url
    link.download = `安全评价报告_${safetyReportData.value['报告基本信息']['报告编号']}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)
    
    alert('报告JSON文件下载成功！')
  } catch (error) {
    console.error('下载报告失败:', error)
    alert('下载报告失败，请重试')
  }
}

// 导出PDF报告
const exportReportToPDF = async () => {
  if (!currentEvaluationId.value) {
    alert('请先创建或选择一个评价记录')
    return
  }
  
  try {
    isExportingPDF.value = true
    
    // 使用统一的报告服务导出PDF
    const { ReportService } = await import('../utils/reportService')
    await ReportService.exportReport(currentEvaluationId.value, {
      filename: `矿山安全评价报告_${safetyReportData.value?.['报告基本信息']?.['报告编号'] || '未知'}.pdf`,
      format: 'pdf'
    })
    
    alert('PDF报告导出成功！')
    
  } catch (error) {
    console.error('导出PDF失败:', error)
    alert('导出PDF失败，请确保网络连接正常并重试')
  } finally {
    isExportingPDF.value = false
  }
}


// 导出报告
const exportReport = async () => {
  if (!currentEvaluationId.value) return
  
  try {
    isExporting.value = true
    const response = await api.evaluation.exportReport(currentEvaluationId.value)
    
    if (response.success) {
      // 这里可以处理报告下载逻辑
      console.log('报告数据:', response.data)
      alert('报告生成成功！\n报告编号: ' + response.data.evaluation_info['评价编号'])
    }
  } catch (error) {
    console.error('导出报告失败:', error)
    alert('导出失败，请重试')
  } finally {
    isExporting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(evaluationForm, {
    evaluation_id: '',
    evaluation_date: new Date().toISOString().split('T')[0],
    evaluator_name: '',
    mine_name: '',
    region: '',
    evaluation_category: '',
    
    // 新增矿山基本信息字段
    affiliated_enterprise: '',
    production_capacity: 100,
    service_life: 30,
    development_methods: [],
    transport_method: '',
    
    // 生产系统信息
    current_production_system: 'mining_system',
    production_systems: {
      mining_system: {
        system_name: '开采系统',
        function_description: '矿石开采',
        main_facilities: '掘进机、采煤机',
        operation_status: 'normal',
        safety_hazards: '顶板监测需加强'
      },
      ventilation_system: {
        system_name: '通风系统',
        function_description: '矿井通风',
        main_facilities: '主扇风机、局部通风机',
        operation_status: 'normal',
        safety_hazards: '通风阻力较大'
      },
      gas_prevention_system: {
        system_name: '瓦斯防治系统',
        function_description: '瓦斯监测与防治',
        main_facilities: '瓦斯监测仪、抽放设备',
        operation_status: 'normal',
        safety_hazards: '监测点覆盖不全'
      },
      drainage_system: {
        system_name: '排水系统',
        function_description: '矿井排水',
        main_facilities: '主排水泵、水仓',
        operation_status: 'normal',
        safety_hazards: '排水能力需提升'
      },
      hoisting_transport_system: {
        system_name: '提升运输系统',
        function_description: '物料提升运输',
        main_facilities: '提升机、运输机',
        operation_status: 'normal',
        safety_hazards: '提升设备老化'
      },
      power_system: {
        system_name: '供电系统',
        function_description: '矿井供电',
        main_facilities: '变压器、配电柜',
        operation_status: 'normal',
        safety_hazards: '供电线路需检修'
      },
      fire_explosion_prevention_system: {
        system_name: '防火防爆系统',
        function_description: '防火防爆',
        main_facilities: '消防设备、防爆设备',
        operation_status: 'normal',
        safety_hazards: '消防设备配置不足'
      }
    },
    
    // 15个安全指标
    worker_safety_awareness: 75.0,
    management_capability: 80.0,
    mining_equipment_integrity: 85.0,
    ventilation_equipment_integrity: 90.0,
    gas_monitoring_equipment_integrity: 88.0,
    fire_prevention_equipment_integrity: 82.0,
    drainage_equipment_integrity: 87.0,
    hoisting_equipment_integrity: 91.0,
    power_system_integrity: 89.0,
    air_supply_demand_ratio: 78.0,
    roof_management_difficulty: 70.0,
    coal_spontaneous_combustion_tendency: 65.0,
    safety_management_implementation: 83.0,
    emergency_response_completeness: 77.0,
    safety_inspection_implementation: 81.0,
  })
  
  currentEvaluationId.value = null
  evaluationResult.value = null
}

// 获取安全等级样式类
const getSafetyLevelClass = (level: string) => {
  if (level?.includes('A级') || level?.includes('优秀')) return 'level-a'
  if (level?.includes('B级') || level?.includes('良好')) return 'level-b'
  if (level?.includes('C级') || level?.includes('一般')) return 'level-c'
  if (level?.includes('D级') || level?.includes('较差')) return 'level-d'
  return 'level-default'
}

// 组件挂载时加载默认值
onMounted(() => {
  loadDefaultValues()
})
</script>

<style scoped>
/* 页面头部样式增强 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

/* 历史评价列表样式 */
.evaluation-history {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  margin-bottom: 30px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f2f5;
}

.evaluation-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.evaluation-card {
  background: white;
  border: 1px solid #e8eaed;
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.evaluation-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0,0,0,0.15);
  border-color: #667eea;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h4 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.evaluation-id {
  background: #667eea;
  color: white;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: bold;
}

.card-body p {
  margin: 8px 0;
  color: #5a6c7d;
  font-size: 14px;
}

.card-footer {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #f0f2f5;
}

.safety-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.safety-score {
  font-weight: bold;
  color: #34495e;
}

/* 指标分类样式增强 */
.indicators-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 30px;
}

.indicator-category {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #e9ecef;
}

.indicator-category h4 {
  color: #495057;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #dee2e6;
  font-size: 18px;
}

.indicator-help {
  margin-left: 8px;
  color: #6c757d;
  cursor: help;
}

.indicator-desc {
  color: #6c757d;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

/* 安全等级样式 */
.safety-level {
  font-size: 24px;
  font-weight: bold;
  padding: 12px 24px;
  border-radius: 8px;
  text-align: center;
}

.level-a { background: #d4edda; color: #155724; }
.level-b { background: #d1ecf1; color: #0c5460; }
.level-c { background: #fff3cd; color: #856404; }
.level-d { background: #f8d7da; color: #721c24; }
.level-e { background: #f5c6cb; color: #721c24; }
.level-default { background: #e2e3e5; color: #495057; }

/* 结果卡片样式 */
.result-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.result-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  text-align: center;
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  border: 1px solid #e9ecef;
}

.result-card h4 {
  color: #6c757d;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: 600;
}

.safety-score, .evaluation-info {
  font-size: 28px;
  font-weight: bold;
  color: #495057;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #6c757d;
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}

/* 安全报告弹窗样式 */
.report-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
  backdrop-filter: blur(3px);
}

.report-modal {
  background: white;
  border-radius: 16px;
  width: 95%;
  max-width: 1200px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 30px;
  border-bottom: 2px solid #e9ecef;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 16px 16px 0 0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 10px;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: scale(1.1);
}

.modal-body {
  flex: 1;
  overflow-y: auto;
  padding: 30px;
}

.report-content {
  max-width: 100%;
}

.report-section {
  margin-bottom: 30px;
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
}

.report-section h4 {
  color: #2c3e50;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  border-bottom: 2px solid #3498db;
  padding-bottom: 8px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px;
  background: white;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.info-item .label {
  font-weight: 600;
  color: #495057;
  min-width: 120px;
}

.info-item .value {
  color: #2c3e50;
  flex: 1;
}

.safety-result {
  display: flex;
  align-items: center;
  gap: 30px;
  flex-wrap: wrap;
}

.safety-level-display {
  font-size: 32px;
  font-weight: bold;
  padding: 20px 30px;
  border-radius: 12px;
  text-align: center;
  min-width: 200px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}

.safety-details {
  flex: 1;
  min-width: 300px;
}

.safety-details p {
  margin-bottom: 10px;
  font-size: 16px;
  color: #495057;
}

/* 指标表格样式 */
.indicators-table {
  overflow-x: auto;
  background: white;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.indicators-table table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.indicators-table th,
.indicators-table td {
  padding: 12px 8px;
  text-align: center;
  border-bottom: 1px solid #dee2e6;
}

.indicators-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #495057;
  position: sticky;
  top: 0;
  z-index: 1;
}

.indicators-table .low-score {
  background: #fff3cd;
  color: #856404;
  font-weight: bold;
}

/* 整改建议样式 */
.remediation-suggestions {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.suggestion-item {
  background: white;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #dee2e6;
  border-left: 4px solid #dc3545;
}

.suggestion-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-wrap: wrap;
  gap: 10px;
}

.indicator-name {
  font-weight: 600;
  color: #2c3e50;
  font-size: 16px;
}

.suggestion-condition {
  margin-bottom: 12px;
  color: #6c757d;
  font-size: 14px;
}

.suggestion-content {
  color: #495057;
  line-height: 1.6;
  font-size: 15px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 20px 30px;
  border-top: 1px solid #e9ecef;
  background: #f8f9fa;
  border-radius: 0 0 16px 16px;
}

/* 复选框和单选框样式 */
.checkbox-group, .radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-top: 8px;
}

.checkbox-label, .radio-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-weight: normal;
  color: #495057;
  margin: 0;
}

.checkbox-label input[type="checkbox"],
.radio-label input[type="radio"] {
  margin: 0;
  cursor: pointer;
}

/* 生产系统信息样式 */
.production-system-container {
  margin-top: 20px;
}

.selected-system-form {
  background: #f8f9fa;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e9ecef;
  margin-top: 20px;
  transition: all 0.3s ease;
}

.selected-system-form:hover {
  box-shadow: 0 4px 15px rgba(0,0,0,0.1);
  border-color: #667eea;
}

.selected-system-form h4 {
  color: #2c3e50;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #dee2e6;
  font-size: 18px;
  font-weight: 600;
}

.system-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.system-form .form-group {
  margin-bottom: 0;
}

.system-form textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ced4da;
  border-radius: 6px;
  font-size: 14px;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
}

.system-form textarea:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

/* 表单网格优化 */
.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .indicators-grid {
    grid-template-columns: 1fr;
  }
  
  .evaluation-cards {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    text-align: center;
  }
  
  .header-actions {
    margin-top: 15px;
  }
  
  .report-modal {
    width: 98%;
    max-height: 95vh;
  }
  
  .modal-body {
    padding: 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .safety-result {
    flex-direction: column;
    text-align: center;
  }
  
  .safety-level-display {
    font-size: 24px;
    padding: 15px 20px;
    min-width: auto;
  }
  
  .indicators-table {
    font-size: 12px;
  }
  
  .indicators-table th,
  .indicators-table td {
    padding: 8px 4px;
  }
  
  .suggestion-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .modal-footer {
    flex-direction: column;
  }
  
  .selected-system-form {
    padding: 15px;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .checkbox-group, .radio-group {
    flex-direction: column;
    gap: 10px;
  }
}
</style>